<template>
  <div class="pagestyle">
    <list_controller
      ref="zujianname"
      :options="state.options"
      pageName="历史分站"
    >
      <template v-slot:opraCurdBtn1="row">
        <el-button
          class="tableFontSize"
          type="primary"
          link
          size="small"
          @click="lookBtn(row.row.row)"
          >查看</el-button
        >
        <!-- <span>
          <el-button class="tableFontSize" type="primary" link size="small" @click="lookBtn(row.row.row)">查看</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="editBtn(row.row.row)">编辑</el-button>
          <el-button class="tableFontSize" type="primary" link size="small" @click="deleteBtn(row.row.row)">删除
          </el-button>
        </span> -->
      </template>
      <template v-slot:opraCurdBtnAll>
        <!-- <el-button class="btn" type="primary" link @click="addBtn('mul')">
          <el-icon style="margin-right: 2px;">
            <svg-icon class-name="search-icon" icon-class="addtotal" />
          </el-icon>新增
        </el-button>
        <el-button class="btn" type="primary" link @click="deleteBtn('mul')">
          <el-icon>
            <DeleteFilled />
          </el-icon>删除
        </el-button> -->
      </template>
    </list_controller>
    <!-- 新增弹框 -->
    <teleport to="body">
      <vxe-modal
        esc-closable
        destroy-on-close
        :lock-view="false"
        :width="660"
        :height="auto"
        v-model="state.addModal"
        resize
        :mask="true"
      >
        <template #title>
          <div class="w100 h100 fsc mask_title">{{ state.modalTitle }}</div>
        </template>
        <template #default>
          <div class="form_box">
            <el-form
              ref="formRef"
              :model="state.formData"
              :rules="state.rules"
              label-position="top"
            >
              <el-row :gutter="20">
                <el-col :span="8">
                  <el-form-item label="类型名称" prop="stationTypeName">
                    <el-input
                      v-model="state.formData.stationTypeName"
                      placeholder="请输入"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="分站模式" prop="stationModelId">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formData.stationModelId"
                      placeholder="请选择"
                      @change="stationModelChange"
                    >
                      <el-option
                        v-for="item in state.stationmodelList"
                        :key="item.id"
                        :label="item.stationModelName"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="输入口数量" prop="stationInNum">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formData.stationInNum"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in state.stationInNumList"
                        :key="item"
                        :label="item"
                        :value="item"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="输出口数量" prop="stationOutNum">
                    <el-select
                      clearable
                      filterable
                      v-model="state.formData.stationOutNum"
                      placeholder="请选择"
                    >
                      <el-option
                        v-for="item in state.stationOutNumList"
                        :key="item"
                        :label="item"
                        :value="item"
                      >
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="16">
                  <el-form-item label="分站类型图片上传" prop="imagePath">
                    <el-upload
                      v-model:file-list="state.fileList"
                      action
                      :before-upload="beforeUpload"
                      :http-request="uploadHttpRequestAdd"
                      ref="upload"
                      list-type="picture"
                      :on-preview="handlePictureCardPreview"
                    >
                      <el-button type="primary">
                        <svg-icon
                          class-name="search-icon"
                          icon-class="photo"
                        />上传图片</el-button
                      >
                      <template #tip>
                        <div class="el-upload__tip">
                          上传图片支持jpg/png等，大小不超过 500kb
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <!-- <el-col :span="8">
                  <img v-if="state.formData.imagePath" style="width:60px;height:60px;"
                    :src="state.formData.imagePath" />
                </el-col> -->
              </el-row>
            </el-form>
            <div class="form_footer">
              <el-button @click="cancel">取消</el-button>
              <el-button type="primary" @click="submitForm"> 确定 </el-button>
            </div>
          </div>
        </template>
      </vxe-modal>
    </teleport>
    <!-- 详情 -->
    <el-drawer
      v-model="state.drawerShow"
      direction="rtl"
      size="40%"
      close-on-click-modal
      :modal="true"
    >
      <template #header="{ close, titleId, titleClass }">
        <h4 class="mask_sub_title">
          <svg-icon class-name="search-icon" icon-class="dot" /><span
            >分站信息</span
          >
        </h4>
      </template>
      <div>
        <el-row :gutter="20">
          <el-col :span="24" style="text-align: center">
            <div
              class="img_box"
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <img src="@/assets/images/keranqiti/远程控制.png" alt="" />
              <div
                style="
                  display: flex;
                  flex-direction: column;
                  align-items: center;
                  margin-left: 10px;
                "
              >
                <div
                  style="
                    background-color: #358cf0;
                    color: #fff;
                    font-size: 12px;
                    width: 40px;
                  "
                >
                  {{ state.drawDetailData.acquisitionBoardTypeName }}
                </div>
                <div style="margin-top: 5px; font-weight: 700">
                  {{ state.drawDetailData.substationNumber }}
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="text-align: center">
          <el-col :span="24">
            <div
              style="
                width: 500px;
                margin: 30px 0;
                margin-left: 50%;
                transform: translate(-50%);
                display: flex;
                justify-content: space-between;
              "
            >
              <div style="text-align: center; font-size: 12px">
                <div style="color: rgba(62, 70, 79, 0.6)">操作类型</div>
                <div>{{ state.drawDetailData.operation }}</div>
              </div>
              <div style="text-align: center; font-size: 12px">
                <div style="color: rgba(62, 70, 79, 0.6)">IP:端口</div>
                <div>{{ state.drawDetailData.ipAddress }}</div>
              </div>
              <div style="text-align: center; font-size: 12px">
                <div style="color: rgba(62, 70, 79, 0.6)">安装时刻</div>
                <div>{{ state.drawDetailData.startTime }}</div>
              </div>
              <div style="text-align: center; font-size: 12px">
                <div style="color: rgba(62, 70, 79, 0.6)">安装地点</div>
                <div>{{ state.drawDetailData.address }}</div>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row :gutter="20" style="margin-top: 10px">
          <el-col :span="24">
            <p class="drawer_sub_title">
              <span class="sub_title_line">测点</span>
            </p>
          </el-col>
          <el-col :span="24">
            <!-- <p class="fsc">
              <span class="wn">编号</span>
              <el-input style="width:200px;margin:0 10px;" v-model="state.options1.queryList.stationCode" clearable
                placeholder="请输入">
              </el-input>
              <el-button type="primary" @click="yinyonClick">查询</el-button>
              <el-button type="info" @click="reset">重置</el-button>
            </p> -->
            <el-table
              :data="state.cedianTableData"
              border
              stripe
              height="300"
              row-class-name="rowHeight"
              cell-class-name="cellBorder"
              header-row-class-name="header"
              header-cell-class-name="header"
              class="table tableFontSize"
              :header-row-style="{
                backgroundColor: isDark ? '#2b5477' : '#e3effe',
              }"
            >
              <!-- <el-table-column type="index" label="编号"/> -->
              <el-table-column show-overflow-tooltip prop="code" label="编号">
                <template #default="{ row }">
                  <div
                    style="
                      display: flex;
                      align-items: center;
                      justify-content: center;
                    "
                  >
                    <!-- <img src="@/assets/images/home/五角星.svg" alt="" /> -->
                    <span style="margin-left: 5px">{{ row.pointNumber }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                show-overflow-tooltip
                prop="installPlace"
                label="安装地点"
              />
              <el-table-column
                show-overflow-tooltip
                prop="pointName"
                label="名称"
              />
              <el-table-column
                sortable=""
                show-overflow-tooltip
                prop="realTimeValue"
                label="监测值"
              />
              <!-- <el-table-column show-overflow-tooltip prop="num3" label="单位" /> -->
              <el-table-column
                show-overflow-tooltip
                prop="highFaultValue"
                label="高/低报警"
              >
                <template #default="{ row }">
                  <!-- highFaultValue   lowFaultValue -->
                  {{ row["highFaultValue"] }} / {{ row["lowFaultValue"] }}
                </template>
              </el-table-column>
              <!-- <el-table-column
              show-overflow-tooltip
              prop="statusName"
              label="状态"
            >
              <template #default="scope">
                <span v-if="scope.row.alarm == true" style="color: red">报警</span>
                <span v-if="scope.row.calibration == true">标校</span>
                <span v-if="scope.row.error == true" style="color: red">故障</span>
                <span v-if="scope.row.offLine == true" style="color: red">断线</span>
                <span v-if="scope.row.powerOff == true">断电</span>
              </template>
            </el-table-column> -->
              <el-table-column show-overflow-tooltip prop="" label="操作">
                <template #default="{ row }">
                  <!-- <img src="@/assets/images/home/标校折线图.svg" alt="" /> -->
                  <el-button type="text" @click="btnClick(row)"
                    >测点详情</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <div style="margin-top: 10px;display: flex;justify-content: end;">
              <el-pagination
              class="pages globalFontSize"
              v-model:current-page="state.page.currentPage"
              v-model:page-size="state.page.pageSize"
              :page-sizes="[10, 20, 30, 40]"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="state.page.total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
            </div>
          </el-col>
        </el-row>
      </div>
    </el-drawer>
    <el-dialog v-model="state.dialogVisiblepictureCardPreview">
      <img :src="state.dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup>
import list_controller from "@/components/commonCom/list_controller";
import { computed, onMounted, reactive } from "vue";
import { table_headers } from "@/components/commonCom/table_headers";
import axios from "@/utils/request";
import usePagesStore from "@/store/modules/pages";
import { getsubstationmodel, fileupload } from "@/api/config";
import { useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const store = usePagesStore();
const router = useRouter();
const route = useRoute();
let previewHttps = import.meta.env.VITE_APP_HTTP;
components: {
  list_controller;
}
const upload = ref(null);
let state = reactive({
  page: {
    currentPage: 1,
    pageSize: 10,
    total: 0,
  },
  fileList: [],
  dialogVisiblepictureCardPreview: false,
  dialogImageUrl: "",
  options: {
    isShowCaozuo: true,
    tableheads: computed(() => table_headers.historyDeviceSubstation),
    tableheads2: computed(() => table_headers.historyStatsPoint), //弹层表头
    queryList: {
      dropdownUrl: "",
      querys: [
        {
          field: "substationNumber",
          title: "分站编号",
          type: "input",
          binddata: "",
        },
        {
          field: "ipAddress",
          title: "IP端口",
          type: "input",
          binddata: "",
        },
        {
          field: "replaceId",
          title: "安装地点",
          type: "select",
          binddata: "",
          options: [],
        },
        {
          field: "time",
          title: "时间",
          type: "startendtime",
          binddata: "",
        },
        {
          field: "operateType",
          title: "操作类型",
          type: "select",
          binddata: "",
          options: [
            {
              label: "新增",
              value: "1",
            },
            {
              label: "编辑",
              value: "2",
            },
            {
              label: "删除",
              value: "3",
            },
          ],
        },
      ],
      queryMap: new Map([
        ["sensorTypeId", "safety_pointType"],
        ["deviceTypeId", "safety_deviceType"],
        ["alarmTypeId", "alarmType"],
      ]),
    },
    dataUrl: "/gas/substation/getHistorySubstation",
    descUrl: "/history/substation/",
    delUrl: "/substation/type/deleteStation",
    addUrl: "/substation/type/addStation",
    editUrl: "/substation/type/editStation",
  },
  // 表单
  addModal: false,
  modalTitle: "新增分站类型",
  drawerShow: false,
  formRef: null,
  formData: {},
  cedianTableData: [],
  drawDetailData: {},
  rules: {
    stationTypeName: [
      {
        required: true,
        message: "请输入类型名称",
        trigger: "blur",
      },
    ],
    stationModelId: [
      {
        required: true,
        message: "请输入通风类型",
        trigger: "change",
      },
    ],
    stationInNum: [
      {
        required: true,
        message: "请选择传感器编号",
        trigger: "change",
      },
    ],
    stationOutNum: [
      {
        required: true,
        message: "请输入报警浓度",
        trigger: "change",
      },
    ],
  },
  editId: undefined,
  stationmodelList: [],
  stationInNumList: [],
  stationOutNumList: [],
  options1: {
    tableheads: computed(() => table_headers.quoteStation),
    queryList: {
      autoSearch: true,
      dropdownUrl: "",
      stationCode: "",
      stationTypeId: "",
      querys: [
        {
          field: "stationCode",
          title: "编号",
          type: "input",
          binddata: "",
        },
      ],
      queryMap: new Map([
        ["sensorTypeId", "safety_pointType"],
        ["deviceTypeId", "safety_deviceType"],
        ["alarmTypeId", "alarmType"],
      ]),
    },
    dataUrl: "/substation/type/quote",
  },
});
// 查看按钮
function lookBtn(row) {
  state.drawerShow = true;
  axios.post(state.options.descUrl + row.id).then((res) => {
    if (res.code == 200) {
      state.drawDetailData = res.data;
      // state.options1.queryList.stationTypeId = res.data.id
    }
  });
  getCedianList();
}
const handleSizeChange = (val) => {
  console.log(`每页 ${val} 条`);
  state.page.pageSize = val;
  getCedianList();
};
const handleCurrentChange = (val) => {
  console.log(`当前页: ${val}`);
  state.page.currentPage = val;
  getCedianList();
};
function getCedianList() {
  axios
    .post("/history/stats/point/list", {
      pageNum: state.page.currentPage,
      pageSize: state.page.pageSize,
    })
    .then((res) => {
      if (res.code == 200) {
        state.cedianTableData = res.rows;
        state.page.total = res.total;
      }
    });
}
function btnClick(row) {
  console.log(row, "row");
  router.push({
    path: "/jcpz/fzjcd",
    query: {
      id: row.pointId,
      pointName: row.pointName,
    },
  });
}

function yinyonClick() {
  axios
    .post("/substation/type/quote", {
      stationTypeId: state.options1.queryList.stationTypeId,
      stationCode: state.options1.queryList.stationCode,
    })
    .then((res) => {
      if (res.code == 200) {
        state.formData.stationBasicDtoList = res.data.list;
      }
    });
}

function reset() {
  state.options1.queryList.stationCode = "";
  axios
    .post("/substation/type/quote", {
      stationTypeId: state.options1.queryList.stationTypeId,
      stationCode: state.options1.queryList.stationCode,
    })
    .then((res) => {
      if (res.code == 200) {
        state.formData.stationBasicDtoList = res.data.list;
      }
    });
}
// 新增按钮
function addBtn(row) {
  state.modalTitle = "新增分站类型";
  state.addModal = true;
  state.formData = {};
  state.editId = undefined;
  state.fileList = [];
}
function LastStr(str) {
  if (str) {
    let index = str.lastIndexOf("/");
    str = str.substring(index + 1, str.length);
    return str;
  }
}
// 编辑按钮
function editBtn(row) {
  state.modalTitle = "编辑地点类型";
  state.addModal = true;
  axios.post(state.options.descUrl + row.id).then((res) => {
    if (res.code == 200) {
      state.formData = res.data;
      state.fileList = [
        {
          name: LastStr(state.formData.imagePath),
          url: state.formData.imagePath,
        },
      ];
      state.editId = res.data.id;
    }
  });
}

function deleteBtn(row) {
  let ids = [];
  if (row != "mul") {
    ids = [row.id];
  } else {
    if (store.records.length > 0) {
      ids = store.records.map((item) => {
        return item.id;
      });
    } else {
      proxy.$modal.msgSuccess("请先勾选所要删除数据!");
    }
  }
  if (ids.length > 0) {
    axios.post(state.options.delUrl, ids).then((res) => {
      if (res.code == 200) {
        proxy.$refs["zujianname"].getData();
        state.addModal = false;
        proxy.$modal.msgSuccess(res.msg);
        store.records = [];
      }
    });
  }
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (state.editId) {
        state.formData.id = state.editId;
        axios.post(state.options.editUrl, state.formData).then((res) => {
          if (res.code == 200) {
            proxy.$refs["zujianname"].getData();
            state.addModal = false;
            proxy.$modal.msgSuccess(res.msg);
          }
        });
      } else {
        axios.post(state.options.addUrl, state.formData).then((res) => {
          if (res.code == 200) {
            proxy.$refs["zujianname"].getData();
            state.addModal = false;
            proxy.$modal.msgSuccess(res.msg);
          }
        });
      }
    }
  });
}
function cancel() {
  state.addModal = false;
}

function getsubstationmodelList() {
  let arr = [];
  getsubstationmodel().then((res) => {
    state.stationmodelList = res.data;
    state.stationmodelList.forEach((item) => {
      arr.push({
        value: item.id,
        label: item.stationModelName,
      });
      state.options.queryList.querys[1].options = arr;
    });
  });
}

function stationModelChange(val) {
  state.stationmodelList.forEach((item) => {
    if (item.id == val) {
      state.stationInNumList = item.stationInNumList;
      state.formData.stationInNum = item.stationInNumList[0];
      state.stationOutNumList = item.stationOutNumList;
      state.formData.stationOutNum = item.stationOutNumList[0];
    }
  });
}
// getsubstationmodelList()
const fileType = ["jpg", "png", "gif", "jpg", "jpeg"]; // 允许的文件类型
const uploadHttpRequestAdd = (data) => {
  upload.value.clearFiles();
  const formData = new FormData();
  formData.append("file", data.file);
  fileupload(formData).then((res) => {
    state.formData.imagePath = previewHttps + res.fileName;
    state.fileList.push({
      name: res.originalFilename,
      url: state.formData.imagePath,
    });
    proxy.$modal.msgSuccess(res.msg);
  });
};
const beforeUpload = (file) => {
  //上传前的钩子
  if (file.type != "" || file.type != null || file.type != undefined) {
    //截取文件的后缀，判断文件类型
    const FileExt = file.name.replace(/.+\./, "").toLowerCase();
    // 计算文件的大小
    const isLt5M = file.size / 1024 < 500; //这里做文件大小限制
    //如果大于500kb
    if (!isLt5M) {
      proxy.$modal.msgWarning("上传文件大小超过限制!");
      upLoading.value = 0;
      return false;
    }
    //如果文件类型不在允许上传的范围内
    if (fileType.includes(FileExt)) {
      return true;
    } else {
      proxy.$modal.msgWarning("上传文件格式不正确!");
      upLoading.value = 0;
      return false;
    }
  }
};
function handlePictureCardPreview(uploadFile) {
  state.dialogVisiblepictureCardPreview = true;
  state.dialogImageUrl = uploadFile.url;
}
function getSelectList() {
  let arr = [];
  axios.post("/gas/place/list",{}).then((res) => {
    arr = res.rows?.map((item) => {
      return { value: item.id+'', label: item.address };
    });
    state.options.queryList.querys[2].options = arr;
  });
}
onMounted(() => {
  getSelectList();
});
</script>
<style lang="scss" scoped>
::v-deep .el-drawer {
  .querycss {
    .fsc {
      &:nth-child(2) {
        display: none;
      }
    }
  }

  .table_box {
    .fsc {
      display: none;
    }
  }
}
</style>